<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Api\V1;

use Think\Model;

class DepositOrder
{
    public $login = false; //是否需要登录才能访问该接口
    public $title = "010保证金下单ok";
    public $group = '保证金';
    public $desc = "";

    public $input = [
        'id' => 'required;int;label=合同',
    ];

    public $output = [
        'order_no' => 'label=订单号;',
    ];

    public function run($param, $uid, $login_info)
    {
        $contact = M('house_contract')->where(['id' => $param['id']])->find();
        $result = M('margin_order')->where(['contact_code' => $contact['code']])->find();
        if(!$result) throw new \Exception('缴费记录不存在');
        if($result['pay_status'] == 1) throw new \Exception('已缴费');
        $order_no = $this->genOrderNo();
        $flag = M('margin_order')->where(['id' => $result['id']])
            ->save(['order_no' => $order_no]);
        return [
            'order_no' => $order_no,
        ];
    }

    //生成订单号
    public function genOrderNo()
    {
        $str = substr(md5(microtime(true)), 8, 16);
        $letters = range('a', 'z');
        $arr = array_map(function ($char) use ($letters) {
            return is_numeric($char) ? $char : array_search($char, $letters);
        }, str_split($str));
        return join('', $arr);
    }
}
